package com.jn.exam.ucenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jn.exam.JwtUtils;
import com.jn.exam.MD5Util;
import com.jn.exam.R;
import com.jn.exam.ucenter.entity.Teacher;
import com.jn.exam.ucenter.service.OssFeignService;
import com.jn.exam.ucenter.service.StudentService;
import com.jn.exam.ucenter.service.TeacherService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.jn.exam.JwtUtils.APP_SECRET;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 江南大学1033190417
 * @since 2022-01-13
 */
@RestController
@RequestMapping("/ucenter/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private OssFeignService ossFeignService;

    //学校给的编号登录
    @PostMapping("loginByNumber/{number}")
    public R loginByNumber(@PathVariable("number") String number, String password) {
        password = MD5Util.getMD5(password);
        Teacher teacher = teacherService.loginByNumber(number, password);
        if (teacher != null) {
            if (teacher.getIsDeleted() == Boolean.TRUE) {
                return R.error().message("账号已禁用");
            }
            String token = JwtUtils.getJwtToken(teacher.getId(), teacher.getName());
            return R.ok().message("登录成功").data("token", token);
        }
        return R.error().message("登录失败");
    }

    @PostMapping("getUserInfo")
    public R getUserInfo(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String id = (String) claims.get("id");
        Teacher teacher = teacherService.getById(id);
        if (teacher != null) {
            return R.ok().message("登录成功").data("teacher", teacher);
        } else {
            return R.error().message("登录失败");
        }
    }

    //退出登录
    @PostMapping("loginOut")
    public R loginOut(HttpServletRequest request) {
        return R.ok().message("退出登录");
    }

    //得到老师id
    @GetMapping("getTeacherId")
    public R getTeacherId(HttpServletRequest request){
        String teacherId = JwtUtils.getMemberIdByJwtToken(request);
        return R.ok().data("teacherId",teacherId);
    }

    //用手机号登录
    @PostMapping("loginByPhone/{phone}")
    public R loginByPhone(@PathVariable("phone") String phone, String code) {
        String PHONE = MD5Util.getMD5(phone);
        String CODE = redisTemplate.opsForValue().get(PHONE);
        if (code.equals(CODE)) {
            Teacher teacher = teacherService.loginByPhone(phone);
            if (teacher != null) {
                if (teacher.getIsDeleted() == Boolean.TRUE) {
                    return R.error().message("账号已禁用");
                }
                String token = JwtUtils.getJwtToken(teacher.getId(), teacher.getName(), "");
                Teacher t=new Teacher();t.setId(teacher.getId()).setGmtModified(new Date());
                teacherService.updateById(t);
                return R.ok().message("登录成功").data("token", token).data("teacher", teacher);
            } else {
                return R.error().message("手机号不存在");
            }
        } else {
            return R.error().message("验证码错误");
        }
    }

    //更新
    @PostMapping("update")
    public R updateTeacher(@RequestBody Teacher teacher, HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        teacher.setId(id);
        boolean update = teacherService.updateById(teacher);
        if (update) {
            return R.ok().message("更新成功");
        } else {
            return R.error().message("更新失败");
        }

    }

    //删除
    @DeleteMapping("deleteById")
    public R deleteById(String teacherId){
        boolean removeById = teacherService.removeById(teacherId);
        if (removeById) {
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }

    @ApiOperation("上传用户头像")
    @PostMapping("uploadAvatar")
    public R uploadAvatar(MultipartFile file, HttpServletRequest request) {
        String id = JwtUtils.getMemberIdByJwtToken(request);
        Teacher teacher = teacherService.getById(id);
        if (!StringUtils.isEmpty(teacher.getAvatar())) {
            boolean deleteFileByUrl = ossFeignService.deleteFileByUrl(teacher.getAvatar());
            if (!deleteFileByUrl) {
                return R.error().message("上传失败");
            }
        }
        String url = ossFeignService.uploadOssFile(file);
        teacher.setAvatar(url);
        boolean updateById = teacherService.updateById(teacher);
        if (updateById) {
            return R.ok().message("上传成功");
        }
        return R.error().message("上传失败");
    }


    @ApiOperation("添加一个老师")
    @PostMapping("addOneTeacher")
    public R addOneTeacher(@RequestBody Teacher teacher) {
        boolean save = teacherService.save(teacher);
        if (save) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    @PostMapping("pageTeacher")
    public R pageTeacher(@RequestBody Teacher teacher,long current,long limit){
        QueryWrapper<Teacher> wrapper=new QueryWrapper<>();
        String number = teacher.getNumber();
        String name = teacher.getName();
        Integer age = teacher.getAge();
        Integer sex = teacher.getSex();
        if (!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(number)){
            wrapper.eq("number",number);
        }
        if (age!=null){
            wrapper.eq("age",age);
        }
        if (sex!=null){
            wrapper.eq("sex",sex);
        }
        Page<Teacher> page=new Page<>(current,limit);
        teacherService.page(page,wrapper);
        List<Teacher> teachers = page.getRecords();
        long rows = page.getTotal();
        return R.ok().data("rows",rows).data("teachers",teachers);
    }
}

